<script setup>
  import { io } from 'socket.io-client'
  import { useUserStore } from '@/store/user.js'
  import { baseURL } from '@/utils/http.js'
  import { nextTick, ref } from 'vue'
  import patientInfo from './components/patient-info.vue'
  import notifyInfo from './components/notify-info.vue'
  import messageInfo from './components/message-info.vue'
  import prescriptionInfo from './components/prescription-info.vue'
  import rateInfo from './components/rate-info.vue'
  import { patientConsultOrderDetailAPI } from '@/services/consult.js'
  import lodingImg from './components/loding-Img.vue'
  import roomStatus from './components/room-status.vue'
  //自定义下拉刷新
  const isrefresher = ref(false)
  //加载图片显示
  const showLoadingImg = ref(false)
  // 文字消息
  const textMessage = ref('')
  // 问诊订单详情
  const orderDetail = ref({})
  ;(async () => {
    const res = await patientConsultOrderDetailAPI(props.orderId)
    // 渲染问诊订单数据
    orderDetail.value = res.data.data
  })()
  // 用户登录信息（不具有响应式）
  const { token, userId } = useUserStore()

  // 获取地址中的参数
  const props = defineProps({
    orderId: String
  })
  // 消息列表
  const messageList = ref([])
  // 建立 socket 连接
  const socket = io(baseURL, {
    auth: { token: 'Bearer ' + token },
    query: { orderId: props.orderId },
    transports: ['websocket', 'polling'],
    timeout: 5000
  })
  //初始化滚动条位置
  const scrollTop = ref(0)

  socket.on('chatMsgList', async ({ data }) => {
    isrefresher.value = false
    if (data.length === 0) return uni.utils.toast('没有更多聊天记录了')
    data.reverse()
    for (let v of data) {
      messageList.value.unshift(
        {
          msgType: 31,
          msg: { content: v.createTime },
          id: v.createTime
        },
        ...v.items
      )
    }
    await nextTick()

    scrollTop.value = 10000
  })
  // 接收消息
  socket.on('receiveChatMsg', (message) => {
    // 修改消息为已读
    socket.emit('updateMsgStatus', message.id)
    // 接收到的消息追加到消息列表中
    messageList.value.push(message)
    showLoadingImg.value = false
    nextTick(() => {
      scrollTop.value += 1000
    })
  })
  //监听订单状态变化
  socket.on('statusChange', async () => {
    const res = await patientConsultOrderDetailAPI(props.orderId)
    // 渲染问诊订单数据
    orderDetail.value = res.data.data
  })
  const easyinputConfirm = () => {
    socket.emit('sendChatMsg', {
      // 当前登录用户的ID
      from: userId,
      to: orderDetail.value?.docInfo?.id,
      msgType: 1,
      msg: {
        content: textMessage.value
      }
    })
  }
  const sendMsgImg = async () => {
    const res = await uniCloud.chooseAndUploadFile({
      type: 'image',
      count: 1,
      extension: ['.jpg', '.png', '.gif'],
      onChooseFile() {
        showLoadingImg.value = true
        nextTick(() => {
          scrollTop.value += 1000
        })
      }
    })

    const picture = {
      id: res.tempFiles[0].lastModified,
      url: res.tempFiles[0].url
    }
    socket.emit('sendChatMsg', {
      // 当前登录用户的ID
      from: userId,
      to: orderDetail.value?.docInfo?.id,
      msgType: 4,
      msg: {
        picture
      }
    })
  }
  //下拉刷新
  const refresherrefresh = () => {
    isrefresher.value = true
    socket.emit('getChatMsgList', 20, messageList.value[0].id, props.orderId)
  }
</script>

<template>
  <view class="room-page">
    <room-status
      :status-value="orderDetail.statusValue"
      :countdown="orderDetail.countdown"
      :status="orderDetail.status"
    />
    <scroll-view
      :scroll-top="scrollTop"
      refresher-enabled
      :refresher-triggered="isrefresher"
      @refresherrefresh="refresherrefresh"
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
    >
      <view class="message-container">
        <template v-for="message in messageList" :key="message.id">
          <!-- 患者信息（21） -->
          <patient-info
            v-if="message.msgType === 21"
            :info="message.msg.consultRecord"
          />
          <!-- 医生评价（已评价） -->
          <rate-info
            :evaluateDoc="message.msg.evaluateDoc"
            has-evaluate
            v-if="message.msgType === 24"
          />
          <!-- 消息通知 -->
          <notify-info v-if="message.msgType >= 31" :type="message.msgType">
            {{ message.msg.content }}
          </notify-info>
          <!-- 文字图片消息 -->
          <messageInfo
            v-if="message.msgType <= 4"
            :info="message"
            :type="message.msgType"
          ></messageInfo>
          <!-- 此处将来填充更多代码... -->
          <!-- 电子处方 -->
          <prescription-info
            v-if="message.msgType === 22"
            :info="message.msg.prescription"
          />
          <rate-info
            :order-id="props.orderId"
            v-if="message.msgType === 23"
            :doctor-id="orderDetail.docInfo?.id"
          ></rate-info>
        </template>
        <!-- 此处将来填充更多代码... -->
        <lodingImg :info="message" v-if="showLoadingImg"></lodingImg>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          :disabled="orderDetail.status !== 3"
          :clearable="false"
          v-model="textMessage"
          @confirm="easyinputConfirm"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
        />
        <view class="image-button">
          <uni-icons
            :size="40"
            color="#979797"
            type="image"
            @click="sendMsgImg"
          ></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
  .room-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
    /* #ifdef H5 */
    height: calc(100vh - 44px);
    /* #endif */
    overflow: hidden;
    box-sizing: border-box;
    background-color: #f2f2f2;
  }

  .message-container {
    padding: 0 30rpx 60rpx;
    overflow: hidden;
  }

  .message-bar {
    background-color: red;
    display: flex;
    padding: 30rpx 30rpx calc(env(safe-area-inset-bottom) + 40rpx);
    background-color: #fff;

    :deep(.is-disabled) {
      background-color: transparent !important;
    }

    :deep(.uni-easyinput__content-input) {
      height: 88rpx;
      padding: 0 44rpx !important;
      border-radius: 88rpx;
      color: #3c3e42;
      font-size: 32rpx;
      background-color: #f6f6f6;
    }

    .image-button {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 88rpx;
      width: 88rpx;
      margin-left: 30rpx;
    }

    .uni-button {
      flex: 1;
    }
  }
</style>
